package net.tbao.seckill.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import net.tbao.common.to.mq.SecKillOrderTo;
import net.tbao.common.utils.R;
import net.tbao.common.vo.MenberResponVO;
import net.tbao.seckill.feign.CounponFeignService;
import net.tbao.seckill.feign.ProductFeignSerivce;
import net.tbao.seckill.interceptor.LonginUserInterceptor;
import net.tbao.seckill.service.SeckillService;
import net.tbao.seckill.to.SeckillSkuRedisTo;
import net.tbao.seckill.vo.SeckillSessionsWithSkus;
import net.tbao.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class SeckillServiceImpl implements SeckillService {

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";

    private final String SKUKILL_CACHE_PREFIX = "seckill:skus:";

    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Autowired
    CounponFeignService counponFeignService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ProductFeignSerivce productFeignSerivce;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * 秒杀商品上架
     */
    @Override
    public void uploadSeckillSkuLatest3Day() {
        R latest3Day = counponFeignService.getLatest3Day();
        if (latest3Day.getCode() == 0) {
            //上架商品
            List<SeckillSessionsWithSkus> sessionsData = latest3Day.getData(new TypeReference<List<SeckillSessionsWithSkus>>() {
            });
            //缓存到redis
            //缓存活动信息
            saveSessionInfo(sessionsData);
            //缓存商品信息
            saveSessionsSkuInfo(sessionsData);

        }

    }

    /**
     * 查询当前时间可以参与秒杀的商品的信息
     *
     * @return
     */
    @SentinelResource(value ="getCurrentSeckillSkus" )
    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        long nowTime = new Date().getTime();
        try(Entry entry=SphU.entry("getCurrentSeckillSkus")){
            // 得到缓存中所有以seckill:sessions:开头的信息
            Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
            for (String key : keys) {
                // key => "seckill:sessions:1589248800000_1589263200000"
                String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
                String[] str = replace.split("_");

                Long startTime = Long.parseLong(str[0]);
                Long endTime = Long.parseLong(str[1]);

                if (nowTime >= startTime && nowTime <= endTime) {

                    List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);

                    BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

                    List<String> list = hashOps.multiGet(range);

                    if (list != null && list.size() > 0) {
                        List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                            SeckillSkuRedisTo secKillSkuRedsTo = JSON.parseObject(item, SeckillSkuRedisTo.class);
                            return secKillSkuRedsTo;
                        }).collect(Collectors.toList());
                        return collect;
                    }
                    break;
                }
            }

        }catch (BlockException e) {

        }

            return null;
    }

    /**
     * 获取SKU 秒杀商品预告信息
     *
     * @param skuId
     * @return
     */
    @Override
    public SeckillSkuRedisTo skuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys!=null && keys.size()>0){
            String regx="//d_"+skuId;
            for (String key : keys) {
               if( Pattern.matches(regx,key)){
                   String json = hashOps.get(key);
                   SeckillSkuRedisTo redisTo = JSON.parseObject(json, SeckillSkuRedisTo.class);
                   long time = new Date().getTime();
                  if( time>=redisTo.getStattTime() && time<=redisTo.getEndTime()){

                  }else {
                      redisTo.setRandomCode(null);
                  }
                   return redisTo;
               }
            }
        }
        return null;
    }

    @Override
    public String seckill(String killId, String key, Integer num) {
        MenberResponVO responVO = LonginUserInterceptor.threadLocal.get();
        //获取当前秒杀商品详细信息
        BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if (StringUtils.isEmpty(s)){
            return null;
        }else {
            SeckillSkuRedisTo redisTo = JSON.parseObject(s, SeckillSkuRedisTo.class);
            //校验合法性
            Long stattTime = redisTo.getStattTime();
            Long endTime = redisTo.getEndTime();
            long time = new Date().getTime();
           Long ttl=  endTime-time;
            //校验时间合法性
            if(time>=stattTime && time<=endTime){
                //校验随机码
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId()+"_"+redisTo.getSkuId();
                if (randomCode.equals(key) &&killId.equals(skuId)){
                    //校验购物数量
                    if(num<=redisTo.getSeckillLimit()){
                        //验证是否购买过
                        String redisKey=responVO.getId()+"_"+skuId;
                        //自动过期
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                boolean b = semaphore.tryAcquire(num);
                                if(b) {
                                    //秒杀成功 快速下单 发送MQ消息
                                    String timeId = IdWorker.getTimeId();
                                    SecKillOrderTo secKillOrderTo = new SecKillOrderTo();
                                    secKillOrderTo.setOrderSn(timeId);
                                    secKillOrderTo.setMemberId(responVO.getId());
                                    secKillOrderTo.setNum(num);
                                    secKillOrderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    secKillOrderTo.setSkuId(redisTo.getSkuId());
                                    secKillOrderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", secKillOrderTo);

                                    return timeId;
                                }
                                return null;

                        }else {
                            return null;
                        }
                    }
                }else{
                    return null;
                }
            }else {
                return null;
            }
        }
        return null;
    }

    /**
     * 保存活动信息
     *
     * @param sessionData
     */
    private void saveSessionInfo(List<SeckillSessionsWithSkus> sessionData) {
        if (sessionData != null) {
            sessionData.stream().forEach(session -> {
                Long startTime = session.getStartTime().getTime();
                Long endTime = session.getEndTime().getTime();

                String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;

                // 判断缓存中是否已经存在本次上架的信息了
                Boolean hasKey = stringRedisTemplate.hasKey(key);

                if (!hasKey) {
                    List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());

                    stringRedisTemplate.opsForList().leftPushAll(key, collect);
                }
            });
        }

    }

    /**
     * 保存活动商品信息
     *
     * @param sessionData
     */
    private void saveSessionsSkuInfo(List<SeckillSessionsWithSkus> sessionData) {
        if (sessionData != null) {
            sessionData.stream().forEach(session -> {
                BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

                session.getRelationSkus().stream().forEach(seckillSkuVo -> {

                    if (!ops.hasKey(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString())) {
                        SeckillSkuRedisTo secKillSkuRedsTo = new SeckillSkuRedisTo();
                        // 1、sku基本信息
                        R skuInfo = productFeignSerivce.SkuInfo(seckillSkuVo.getSkuId());
                        if (skuInfo.getCode() == 0) {
                            SkuInfoVo skuInfoVo = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                            });
                            secKillSkuRedsTo.setSkuInfoVos(skuInfoVo);
                        }

                        // 2、sku秒杀信息
                        BeanUtils.copyProperties(seckillSkuVo, secKillSkuRedsTo);

                        // 3、设置当前商品的秒杀时间信息
                        secKillSkuRedsTo.setStattTime(session.getStartTime().getTime());
                        secKillSkuRedsTo.setEndTime(session.getEndTime().getTime());

                        // 4、设置商品的随机码
                        String token = UUID.randomUUID().toString().replace("-", "");
                        secKillSkuRedsTo.setRandomCode(token);

                        // 缓存到redis
                        String json = JSON.toJSONString(secKillSkuRedsTo);
                        ops.put(seckillSkuVo.getPromotionSessionId().toString() + "_" + seckillSkuVo.getSkuId().toString(), json);

                        // 5、使用库存作为分布式信号量 限流
                        RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                        BigDecimal seckillCount = seckillSkuVo.getSeckillCount();
                        int count = Integer.parseInt(seckillCount.toString());
                        // 设置信号量，商品可以秒杀的件数昨为信号量
                        semaphore.trySetPermits(count);
                    }

                });
            });
        }

    }
}
